<template>
  <div class="camera-warpper">
    <div class="video-container">
      <video v-show="show" id="video" width="500px" height="500px" autoplay="autoplay"></video>
      <canvas v-show="!show" id="canvas" width="500px" height="500px"></canvas>
    </div>
    <div class="btns">
      <el-button type="primary" plain v-show="!show" @click="downPhoto">下载</el-button>
      <el-button type="primary" plain v-show="show" @click="takePhoto">拍照</el-button>
      <el-button type="primary" plain v-show="!show" @click="openCamera">重拍</el-button>
      <el-button type="primary" plain v-show="!show" @click="confirmPhoto">使用</el-button>
    </div>
  </div>


</template>

<script>
export default {
  name: "shooting",
  props: ['cameraShootingVisible'],
  data() {
    return {
      constraints: {
        video: {width: 500, height: 500},//视频轨道
        audio: false,//音频轨道
      },
      mediaStream: '',
      show: true,
      imgSrc: '',
      imgFile: '',
      timeName: '',
      isPcShow: true,
      uploadFileSrc: '',


    }
  },
  methods: {
    //判断是手机/平板/电脑
    judgment() {
        var ua = navigator.userAgent,
        isWindowsPhone = /(?:Windows Phone)/.test(ua),
        isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
        isAndroid = /(?:Android)/.test(ua),
        isFireFox = /(?:Firefox)/.test(ua),
        isChrome = /(?:Chrome|CriOS)/.test(ua),
        isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox &&
          /(?:Tablet)/.test(ua)),
        isPhone = /(?:iPhone)/.test(ua) && !isTablet,
        isPc = !isPhone && !isAndroid && !isSymbian;
      return {
        isTablet: isTablet,
        isPhone: isPhone,
        isAndroid: isAndroid,
        isPc: isPc
      }
    },

    // 开启摄像
    openCamera() {
      this.show = true
      //获取video摄像头区域
      let video = document.getElementById("video");
      //这里介绍新的方法，返回一个Promise对象
      //这个promise对象返回成功后的回调函数带一个MediaStream对象作为其参数
      //then()是Promise对象里的方法
      //then()方法是异步执行，当then()前的方法执行完后再执行then()内部程序，避免数据没有获取到
      let promise = navigator.mediaDevices.getUserMedia(this.constraints);
      let that = this;
      promise.then(function (MediaStream) {
        that.mediaStream = MediaStream
        video.srcObject = MediaStream;
        video.play();
      }).catch((err) => {
        // console.error(err);
        this.$notify({
          title: "警告",
          message: "没有开启摄像头权限或浏览器版本不兼容!",
          type: "warning"
        });
      });
    },
    //关闭摄像头权限
    stopCamera() {
      this.mediaStream.getTracks().forEach(track => {
        track.stop();
      });
    },
    //拍照
    takePhoto() {
      //获取Canvas对象
      let video = document.getElementById("video");
      let canvas = document.getElementById("canvas");
      let ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, this.constraints.video.width, this.constraints.video.height);
      this.stopCamera()
      this.getTime()
      this.show = false
    },
    //canvas下载图片
    downPhoto() {
      let canvas = document.getElementById("canvas");
      const MIME_TYPE = "image/png";
      const dlLink = document.createElement('a');


      dlLink.download = this.timeName;
      dlLink.href = canvas.toDataURL(MIME_TYPE);
      dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
      document.body.appendChild(dlLink);
      dlLink.click();
      document.body.removeChild(dlLink);

    },
    // 获取时间用于文件名
    getTime() {
      let now = new Date()
      let y = now.getFullYear()
      let m = now.getMonth() + 1
      let d = now.getDate()
      this.timeName = y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + (now.toTimeString().substr(0, 8)).replace(/:/g, '-');
    },
    //转成file文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type: mime});
    },
    //确定使用该照片
    confirmPhoto() {
      this.imgSrc = canvas.toDataURL("image/png")
      this.imgFile = this.dataURLtoFile(this.imgSrc, this.timeName + ".png");
      this.closeShooting(this.imgSrc, this.imgFile)
    },
    //关闭拍照页面
    closeShooting() {
      this.$emit('closeShooting', this.imgSrc, this.imgFile)
    },
    imgChange(e) {
      console.log('imgChanfe', e.target.files[0]);  //图片文件
      var reader = new FileReader();
      reader.onload = (function (file) {
        return function (e) {
          this.uploadFileSrc = this.result
        };
      })(e.target.files[0]);
      reader.readAsDateURL(e.target.files[0]);
    },


  },
  mounted() {
    var os = this.judgment()
    if (os.isAndroid || os.isPhone) {
      // alert("手机")
      // this.isPcShow=false
      this.openCamera()
    } else if (os.isTablet) {
      // alert("平板")
      // this.isPcShow=false
      this.openCamera()
    } else if (os.isPc) {
      // alert("电脑")
      // this.isPcShow=true
      this.openCamera()
    }
    console.log('os--', os)
  },
  beforeDestroy() {
    this.stopCamera()
  }
}
</script>

<style scoped rel="stylesheet/scss" lang="scss">

video,
canvas {
  width: 500px;
  height: 500px;
  border: 1px solid #ff5415;
  border-radius: 4px;
  margin-left: 5px;
}

.camera-warpper {
  padding: 20px 0;
  width: 100%;
}

.video-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.btns {
  padding: 20px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}


</style>
